package com.eqdd.yiqidian.ui.tongxunlu;

import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.eqdd.floatingmenu.MenuItem;
import com.eqdd.floatingmenu.TopRightMenu;
import com.eqdd.yiqidian.FriendDetailInfoActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.bean.rebuild.FriendApplyResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.DialogStringCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.utils.IMUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.jakewharton.rxbinding.view.RxView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.rong.imkit.RongIM;

/**
 * Created by lvzhihao on 17-4-7.
 */

public class FriendDetailInfoActivity extends BaseActivity {


    private FriendDetailInfoActivityCustom dataBinding;
    private String phone;
    private EditDialogFragment editDialog;
    private FriendApplyResultBean friendBean;

    @Override
    public void setView() {
        initTopRightImage(R.mipmap.more, v -> {
            new TopRightMenu(this)
                    .showIcon(false)
                    .align(TopRightMenu.Align.RIGHT)
                    .addMenuItem(new MenuItem("转发好友"))
                    .addMenuItem(new MenuItem("分享群组"))
                    .setHeight(220)
                    .setWidth(200)
                    .setOnMenuItemClickListener(i -> {

                            }
                    )
                    .showAsDropDown(v, 0, -20);

        });
        RxView.clicks(dataBinding.btAdd)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe((o) -> {
                    showInviteDialog();
                });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        String deal = "";
        if (v.getId() == R.id.bt_reject) {
            deal = "false";
        }
        if (v.getId() == R.id.bt_agree) {
            deal = "true";
        }
        if (!TextUtils.isEmpty(deal)) {
            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.INVITE_FRIEND_DEAL)
                    .params("userGuid", user.getGuid())
                    .params("friendGuid", friendBean.getGuid())
                    .params("type", deal)
                    .execute(new DialogCallBack<HttpResult>(FriendDetailInfoActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                refresh();
                            }
                        }
                    });
        }
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_friend_detail_info);
        initTopTitleBar(View.VISIBLE, "详细资料");

    }

    @Override
    public void initData() {
        phone = getIntent().getStringExtra(Config.UNAME_OR_EQDCODE);
        refresh();
    }

    private void refresh() {
        OkGo.<String>post(HttpConfig.BASE_URL + HttpConfig.SEARCH_FRIEND)
                .params("userGuid", user.getGuid())
                .params("account", phone)
                .execute(new DialogStringCallBack(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        JsonObject asJsonObject = new JsonParser().parse(result).getAsJsonObject();
                        int status = asJsonObject.get("status").getAsInt();
                        ToastUtil.showShort(asJsonObject.get("msg").getAsString());
                        if (status == 200) {
                            HttpResult<List<FriendApplyResultBean>> httpResult = new Gson().fromJson(result, new TypeToken<HttpResult<List<FriendApplyResultBean>>>() {
                            }.getType());
                            if (httpResult.getItems().size() > 0) {
                                friendBean = httpResult.getItems().get(0);
                                updataView(friendBean);
                            }
                        } else if (status == 203) {
                            HttpResult<User> httpResult = new Gson().fromJson(result, new TypeToken<HttpResult<User>>() {
                            }.getType());
                            updataView(httpResult.getItems());
                        } else {
                            finish();
                        }
                    }
                });
    }

    private void updataView(FriendApplyResultBean friendApplyResultBean) {
        ImageUtil.setCircleImage(friendApplyResultBean.getIphoto(), dataBinding.ivPhoto);
        dataBinding.tvName.setText(friendApplyResultBean.getUpname());
        dataBinding.tvPhone.setText(friendApplyResultBean.getUname());
        dataBinding.tvNum.setText("易企点号:" + friendApplyResultBean.getEQDCode());
        dataBinding.tvCompany.setText(friendApplyResultBean.getCom_name());
        dataBinding.tvDepartAndPost.setText(friendApplyResultBean.getDepartName() + " " + friendApplyResultBean.getPostName());
        dataBinding.tvAddress.setText("");
        dataBinding.vImageWatcher.setErrorImageRes(R.mipmap.error_picture);
        dataBinding.ivPhoto.setOnClickListener(v -> {
            ArrayList<ImageView> imageViews = new ArrayList<>();
            imageViews.add(dataBinding.ivPhoto);
            ArrayList<String> strings = new ArrayList<>();
            strings.add(friendApplyResultBean.getIphoto());
            dataBinding.vImageWatcher.show(dataBinding.ivPhoto, imageViews, strings);
        });
        if (friendApplyResultBean.getGuid().equals(user.getGuid())) {
            return;
        }
        if (friendApplyResultBean.getSign() == 0 && friendApplyResultBean.getORD().equals("friend")) {
            dataBinding.llDeal.setVisibility(View.VISIBLE);
            dataBinding.btAdd.setVisibility(View.GONE);
        } else if (friendApplyResultBean.getSign() == 1) {
            dataBinding.llDeal.setVisibility(View.GONE);
            dataBinding.btAdd.setVisibility(View.VISIBLE);
            dataBinding.btAdd.setText("发消息");
            RxView.clicks(dataBinding.btAdd)
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe(v -> {
                        IMUtil.startPrivate(FriendDetailInfoActivity.this,friendApplyResultBean.getGuid(), friendApplyResultBean.getUpname(),friendApplyResultBean.getIphoto());
                    });
        } else {
            dataBinding.llDeal.setVisibility(View.GONE);
            dataBinding.btAdd.setVisibility(View.VISIBLE);
            dataBinding.btAdd.setText("加好友");
            RxView.clicks(dataBinding.btAdd)
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe(v -> {
                        if (editDialog == null) {
                            editDialog = ChooseAlertView.getEditDiglog("附加消息", "我是" + user.getPname(), "让好友知道你是谁", null, null, new EditDialogFragment.OnClickListener() {
                                @Override
                                public void onClick(List<String> contents) {
                                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.INVITE_FRIEND)
                                            .params("userid", user.getGuid())
                                            .params("friendid", friendApplyResultBean.getGuid())
                                            .params("addcontent", contents.get(0))
                                            .execute(new DialogCallBack<HttpResult>(FriendDetailInfoActivity.this) {
                                                @Override
                                                public void onSuccess(Response<HttpResult> response) {
                                                    HttpResult httpResult = response.body();
                                                    ToastUtil.showShort(httpResult.getMsg());
                                                    if (httpResult.getStatus() == 200) {
                                                        finish();
                                                    }
                                                }
                                            });
                                }
                            });
                        }
                        editDialog.show(getSupportFragmentManager(), "addFriend");
                    });
        }
    }

    private void updataView(User userBean) {
        dataBinding.tvName.setText(userBean.getPname());
        dataBinding.tvPhone.setText(phone);
        dataBinding.tvNum.setText("易企点号:" + userBean.getEQDCode());
        dataBinding.tvCompany.setText(userBean.getCompany());
        dataBinding.tvDepartAndPost.setText(userBean.getDepartment() + " " + userBean.getPost());
        dataBinding.tvAddress.setText("");
        ImageUtil.setCircleImage(userBean.getIphoto(), dataBinding.ivPhoto);
        dataBinding.vImageWatcher.setErrorImageRes(R.mipmap.error_picture);
        dataBinding.ivPhoto.setOnClickListener(v -> {
            ArrayList<ImageView> imageViews = new ArrayList<>();
            imageViews.add(dataBinding.ivPhoto);
            ArrayList<String> strings = new ArrayList<>();
            strings.add(userBean.getIphoto());
            dataBinding.vImageWatcher.show(dataBinding.ivPhoto, imageViews, strings);
        });
        if (userBean.getGuid().equals(user.getGuid())) {
            return;
        }
        dataBinding.llDeal.setVisibility(View.GONE);
        dataBinding.btAdd.setVisibility(View.VISIBLE);
        dataBinding.btAdd.setText("添加好友");
        RxView.clicks(dataBinding.btAdd)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(v -> {
                    if (editDialog == null) {
                        editDialog = ChooseAlertView.getEditDiglog("附加消息", "我是" + user.getPname(), "让好友知道你是谁", null, null, contents -> OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.INVITE_FRIEND)
                                .params("userid", user.getGuid())
                                .params("friendid", userBean.getGuid())
                                .params("addcontent", contents.get(0))
                                .execute(new DialogCallBack<HttpResult>(FriendDetailInfoActivity.this) {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        ToastUtil.showShort(httpResult.getMsg());
                                        if (httpResult.getStatus() == 200) {
                                            finish();
                                        }
                                    }
                                }));
                    }
                    editDialog.show(getSupportFragmentManager(), "addFriend");
                });

    }

    private void showInviteDialog() {
        EditText editText = new EditText(this);
        editText.setHintTextColor(getResources().getColor(R.color.hint_color));
        editText.setText("我是" + user.getName());
        editText.setHint("请输入验证信息");
        ChooseAlertView.getEditDiglog("发送好友请求", "请输入验证信息", null, contents -> new HttpPresneter.Builder(HttpConfig.INVITE_FRIEND, BaseBean.class, FriendDetailInfoActivity.this)
                .Params("userid", user.getUname())
                .Params("friendid", phone)
                .Params("content", contents.get(0))
                .Params("iphoto", user.getIphoto())
                .setOnHttpListener(new HttpPresneter.OnHttpListener<BaseBean>() {
                    @Override
                    public void onError(Throwable e) {
                        System.out.println(e.toString());

                    }

                    @Override
                    public void onNext(BaseBean baseBean) {
                        ToastUtil.showShort(baseBean.getMsg());
                        if (baseBean.getStatus() == 200) {
                            finish();
                        }
                        System.out.println(baseBean.toString());
                    }
                })
                .build()
                .post()).show(getSupportFragmentManager(), "alert");
    }

}